# -*- coding: utf-8 -*-
# File : user.py
# Author: taoyahui
# Date : 2021/7/18
from django.http import HttpResponse
import json
from HelloWorld.models import User
import results
from hashlib import md5
from HelloWorld import utils


def create(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    print(res_json)
    if 'username' in res_json and 'password' in res_json and 'address' in res_json and 'role' in res_json:
        username = res_json['username']
        password = res_json['password']
        nickname = res_json['nickname']
        address = res_json['address']
        role = res_json['role']
        encode_passwd = md5(password.encode('utf-8'))
        token = utils.gen_token()

        user = User(username=username,
                    password=encode_passwd.hexdigest(),
                    nickname=nickname,
                    address=address,
                    role=role, token=token)
        user.save()
        return HttpResponse(results.success_result)

    else:
        return HttpResponse(results.system_error_result)


def login(request):
    res_json = json.loads(request.body.decode().replace("'", "\""))
    if 'username' in res_json and 'password'in res_json:
        username = res_json['username']
        password = res_json['password']
        encode_passwd = md5(password.encode('utf-8'))
        user_list = User.objects.filter(username=username)
        if len(user_list) == 0:
            return HttpResponse(json.dumps(results.info_not_exists_result))
        user = user_list[0]
        encode_passwd = md5(password.encode('utf-8'))
        if user.password == encode_passwd.hexdigest():
            gen_dict = {
                'token': user.token,
                'address': 'address',
                'role':user.role
            }
            resp = json.dumps({
                'code': 200,
                'data': gen_dict
            })
        else:
            return HttpResponse(json.dumps(results.system_error_result))
        return HttpResponse(resp)
    else:
        return HttpResponse(json.dumps(results.system_error_result))


def token_verify(request):
    token = request.GET.get('token')
    return_data = json.dumps(results.success_result)
    return HttpResponse(return_data)
